Skip to content

feat(http): api-versioning headers on all responses + multi-version handler support#2683

Merged
jeremydmiller merged 8 commits intoJasperFx:mainfrom
outofrange-consulting:feature/http-versioning-combined
May 7, 2026
Merged

feat(http): api-versioning headers on all responses + multi-version handler support#2683
jeremydmiller merged 8 commits intoJasperFx:mainfrom
outofrange-consulting:feature/http-versioning-combined

Conversation

@outofrange-consulting
Copy link
Copy Markdown

@outofrange-consulting outofrange-consulting commented May 6, 2026

Summary

Combines #2661 and #2662 into a single rebased PR as requested.

Problem 1 — Versioning headers missing on error responses: API versioning headers (Deprecation, Sunset, Link, api-supported-versions) were only emitted on 2xx responses. The header writer ran as a postprocessor that codegen bypassed on early-return paths (validation failures, 404s, etc.).

Fix: Register an ApiVersionHeaderFinalizationPolicy that inserts the writer at middleware position 0 and uses Response.OnStarting to emit headers regardless of status code.

Problem 2 — No multi-version handler support: A handler couldn't serve multiple API versions — each version required a separate class.

Fix: Expand handler chains declaring multiple [ApiVersion] attributes into per-version clones during HttpGraph.DiscoverEndpoints, before policies run. Adds [MapToApiVersion] support for method-level version targeting within multi-version classes. The api-supported-versions header now reflects per-endpoint sibling version unions via ApiVersionMetadata.

Key changes:

  • ApiVersionHeaderFinalizationPolicy — positions header writer above FluentValidation's short-circuit frame
  • MultiVersionExpansion — clones chains per declared version with isolated metadata/attributes
  • ApiVersionResolver.ResolveVersions — returns all declared versions (replaces single-version Resolve)
  • Neutrality check ([ApiVersionNeutral]) now runs before the pre-assigned version guard to correctly handle fluent HasApiVersion() overrides
  • Asp.Versioning.Abstractions floated to [10.0.0, 11.0.0)

Supersedes #2661 and #2662.

Open question

@jeremydmiller With multi-version handlers now available, should we update the RoutePrefix documentation to guide users toward one approach or the other (separate classes per version vs. multi-version handler with [MapToApiVersion])? Could help avoid confusion about when to use which.

Geoffrey MARC and others added 7 commits May 6, 2026 12:39
ApiVersionHeaderWriter now registers headers via Response.OnStarting
from the very first frame of every relevant chain, so versioning
headers (Deprecation, Sunset, Link, api-supported-versions) are
emitted on all framework-produced responses regardless of status code:
2xx, IResult-returning short-circuits, validation ProblemDetails, and
middleware-IResult exits.

Previously the writer ran as a Postprocessor, which Wolverine codegen
skips when MaybeEndWithResultFrame or MaybeEndWithProblemDetailsFrame
returns out of the generated handler — leaving 4xx error paths
without the headers.

A new ApiVersionHeaderFinalizationPolicy is registered in
MapWolverineEndpoints after configure(); it runs last and re-positions
the writer call to chain.Middleware index 0, outranking
FluentValidation / DataAnnotations / RequestId / TenantId frames that
also insert at index 0.

Out of scope: responses produced by the global ASP.NET Core exception
handler bypass the chain pipeline; users wanting headers on 5xx wire
them via separate middleware (documented in versioning.md).

Tests: 4 new integration tests in api_versioning_error_path_header_tests
exercise the four exit paths (404 IResult, 400 validation, 401
middleware short-circuit, success). Sample endpoints added in
WolverineWebApi/ApiVersioning/OrdersV1ErrorPathsEndpoint.cs.
- ApiVersionHeaderFinalizationPolicy: switch to IReadOnlySet for O(1)
  Contains, drop the unreachable re-position branch in favor of a
  Debug.Assert idempotency invariant.
- ApiVersionHeaderWriter: drop per-request tuple boxing in OnStarting
  by re-fetching endpoint metadata + writer from RequestServices in a
  static callback; expose WriteVersioningHeadersTo as a public helper
  so exception-path middleware can reuse the same RFC formatting.
- ApiVersioningPolicy: rename WireHeaderPostprocessors to
  AttachHeaderState, RequiresHeaderWriter to RequiresHeaderEmission,
  _headerProcessedChains to _headerStateChains.
- WolverineWebApi: split OrdersV1ErrorPathsEndpoint.cs into one file
  per type; add OrdersV1ThrowsEndpoint plus a scoped UseExceptionHandler
  on /v1/orders/throws to back the new regression test.
- api_versioning_error_path_header_tests: pin the documented
  out-of-scope (5xx via global exception handler emits no versioning
  headers) and tighten api-supported-versions assertions to the exact
  expected value rather than ContainsKey.
- versioning.md: tighten the 5xx middleware snippet to delegate header
  emission to ApiVersionHeaderWriter.WriteVersioningHeadersTo so the
  source of truth lives in one place.
…eader path

Second-pass review fixes for PR #3.

Production
- Rename ApiVersioningPolicy.ChainsRequiringHeaderWriter to
  ChainsRequiringHeaderEmission to match the rest of the rename pass
  ("header state / emission" terminology). Property was already internal,
  so callers in WolverineHttpEndpointRouteBuilderExtensions are updated
  in lockstep.
- ApiVersionHeaderWriter.WriteAsync now resolves the writer via
  GetRequiredService<T>() inside the OnStarting callback. The previous
  GetService(typeof(...)) silently swallowed null and made lost headers
  invisible. Bootstrap registers the writer unconditionally as a singleton,
  so a missing registration is a programmer error and must fail fast.
- Add inline comments to the early-exit gate and the in-OnStarting re-fetch
  explaining why the writer must re-resolve the endpoint at flush time
  (middleware can re-route the request between frames).
- Mark WriteVersioningHeadersTo with EditorBrowsable(Advanced) and add a
  class-level XML doc explaining the asymmetry between WriteAsync (chain
  frame, locked by codegen) and the sync helper for advanced/middleware use.
- WolverineWebApi/Program.cs: pin placement intent of UseExceptionHandler
  with a "before MapWolverineEndpoints" comment.
- OrdersV1ThrowsEndpoint: throw message now identifies the source and
  flags it as IGNORE for log tailers.

Tests
- New ApiVersionHeaderWriterTests.missing_writer_in_request_services_throws
  pins the new fail-fast contract for the GetRequiredService change.
- New DEBUG-only ApiVersioningPolicyHeaderWiringTests.finalization_assert_-
  fires_when_writer_was_displaced exercises the Debug.Assert invariant
  in ApiVersionHeaderFinalizationPolicy via a throwing TraceListener.
  Guarded by #if DEBUG since the assert is no-op under RELEASE.
- api_versioning_error_path_header_tests:
  - Extract ExpectedSupportedVersions constant for "1.0, 3.0" with a
    pointer to Program.cs:303-306 so config drift produces a clear
    single failure rather than four near-identical ones.
  - Assert response body contains "global-exception-handler" on the 5xx
    test so a future change letting Wolverine answer the throws endpoint
    with its own 500 cannot turn the absent-headers assertion into a
    tautology.

Docs
- versioning.md exception-handler snippet: add the missing
  Microsoft.Extensions.DependencyInjection using and switch to
  GetRequiredService<T>() to match the production change.
Replace the static OnStarting lambda + RequestServices.GetRequiredService
re-resolution with a closure that captures `this` and `context`. The writer
is already resolved from DI by Wolverine's generated handler (MethodCall.For),
so no further service location is needed in the hot path.

Trades the static-lambda micro-optimization for one closure allocation per
request — the same cost ASP.NET Core middleware pays for OnStarting in
general, and the price of being idiomatic.

Removes the now-unreachable missing-writer-in-RequestServices fail-fast test.
…ToApiVersion]

Wolverine.Http now expands handler chains that declare multiple API versions into
one endpoint per version at bootstrap time, before any IHttpPolicy runs. This lets
a single handler method serve several versions (via repeated [ApiVersion]
attributes or class-level [ApiVersion] declarations) while keeping per-version
metadata, routes, and deprecation/sunset policies isolated to each clone.

[MapToApiVersion] is honoured on methods of classes that advertise multiple
versions: the listed subset is registered, with strict validation that every
mapped version exists at class level. Mixing [ApiVersion] and [MapToApiVersion]
on the same method fails fast with a descriptive error.

Per-version OperationId is suffixed with the version to keep ASP.NET Core's
"endpoint names must be globally unique" invariant intact when handlers carry
explicit OperationIds. Each clone receives its own MethodCall instance so
JasperFx codegen wires frame chains independently.
Allow patch and minor updates within the 10.x line so security and bug fixes
flow through automatically while still pinning out of 11.x where breaking
changes might land.
…ordering

Squashed from PR JasperFx#2662 review iterations:
- tighten multi-version metadata isolation and per-clone attribute filtering
- emit per-endpoint api-supported-versions header using sibling version union
- reorder neutrality check before pre-assigned ApiVersion guard
api-supported-versions now reports the per-endpoint sibling version
union instead of the global options-driven fallback. These error-path
endpoints only declare v1 with no v3 sibling at the same route, so
the expected header is "1.0" not "1.0, 3.0".
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants